Skip to content

fix: normalize structured content attributes from third-party spans - #285

Closed
PabloPardoGarcia wants to merge 2 commits into
mainfrom
pablo/rius-1874-structured-content-attributes
Closed

PabloPardoGarcia wants to merge 2 commits into
mainfrom
pablo/rius-1874-structured-content-attributes

Conversation

@PabloPardoGarcia

@PabloPardoGarcia PabloPardoGarcia commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

semantic-conventions-genai #634 requires gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions and gen_ai.tool.definitions to be structured values (maps and arrays) instead of JSON strings. OpenTelemetry Python keeps such values on a span from 1.45. Every export pass read only strings, so a structured value skipped the native media rebuild, and a blob's bytes could reach the backend.

What changes

  • structured_content_as_json (normalization.py) is now the first pass of NormalizingSpanExporter. For these four keys, a mapping, list or tuple is written as its JSON text. Every pass after it then handles the value exactly as it handles that string, so a structured value and its JSON string export the same attributes.
  • The text uses the one JSON encoding (compact, raw UTF-8, no HTML escaping, non-finite numbers become null, lone surrogates escaped). It is not cut at the 32 KB attribute cap, because a string of the same length is not cut either. Past the strip budget it is cut the same way a string past the budget is. This uses a new _serde.json_text, which shares serialize's encoder but skips the final truncate.
  • A blob part's byte content ({"type": "blob", "content": b"..."}, as OTel 1.45 stores bytes) is written as base64, which is how a blob part's JSON carries it. The part is then rebuilt with its byte_size and loses its bytes. Any other byte object becomes the marker, as everywhere else in the SDK.
  • Mappings of any type (for example MappingProxyType) are written as objects. A value the encoder refuses (a cycle, a bytes, tuple or datetime key) never fails the export. Its fallback is the safe repr of the value as it came, not of the base64-converted one, so a blob's bytes are a marker there too (the converted value's repr would carry the base64 as a bare string that neither the media rebuild nor the strip recognises). The base64 form is used only when the whole value encodes (_serde.strict_json_text). Strings, numbers, booleans and lone byte objects are not structured and are left alone. Other keys keep their structured values, as before.

Shared cases

tests/fixtures/semconv/sdk_cases/structured_content.json comes from glassflow/rius-semconv#113 and is vendored here from that branch's commit (de35796). test_sdk_cases.py runs the cases. I'll re-sync from main once #113 merges. This PR's output is the reference for those expected results. The TypeScript SDK has a matching PR.

Events are unchanged. Their attributes still go only through the strip, which already turns byte objects inside maps into markers.

Known follow-ups (not in this PR)

  • Span events with structured content keys. A structured blob on an event attribute whose content is already a base64 string passes through the strip unrecognised. This was true before this PR too; the fix is to run structured_content_as_json on event attributes as well.
  • Float text differs between the SDKs. Python's encoder writes 1.0, 1e-07 and -0.0 where JSON.stringify writes 1, 1e-7 and 0. This was already true of serialize, and the shared cases deliberately hold no integral float and no exponent. The output matches TypeScript byte for byte for the shared cases, not for every float.

Tests

  • tests/test_normalization_structured_content.py, written first and failing before the change. Review follow-up: a blob in a cyclic message list, beside a bytes key and beside a tuple key, through NormalizingSpanExporter. All 3 failed (base64 exported) before the fallback fix. A test that goes through a real tracer skips on OTel versions that drop mapping attributes. The floor job (OTel 1.25) passes with that one skip.
  • Mutation check: turning off the blob base64 step fails 2 tests. Writing with serialize instead of json_text fails 3 tests (the cap test among them). Falling back to the converted value again fails the 3 new tests.
  • ruff check, ruff format --check, mypy and pytest (2936 passed, 22 skipped, 1 xfailed) all pass locally.

Closes RIUS-1874

The GenAI conventions now ask for gen_ai.input.messages,
gen_ai.output.messages, gen_ai.system_instructions and
gen_ai.tool.definitions as maps and arrays, which OpenTelemetry Python keeps
on spans from 1.45. Every export pass read only strings, so a structured value
skipped the media rebuild and its blob bytes could reach the backend.

The exporter now writes such a value as its JSON text first, in the one
encoding and uncut, and normalizes it exactly as that string. A blob part's
byte content is written as its base64, so the part keeps its byte_size and
loses its bytes; any other byte object is the marker.
@PabloPardoGarcia

Copy link
Copy Markdown
Member Author

Automated review

The design holds up. Converting to the one JSON text first and then running every existing pass on it is the right shape: the media rebuild and the strip stay in one place, and the structured == its JSON string invariant is easy to test. I checked out 5dfcaf6 and ran the new tests plus test_sdk_cases.py (195 passed on OTel 1.45.2). I also confirmed that a real 1.45 tracer stores the value as tuple[dict] and that it comes out rebuilt with byte_size. CI, otel-floor included, is green. I also ran adversarial inputs through NormalizingSpanExporter. Deep nesting (100 to 3000 levels), values over 1 MB, released memoryviews, MappingProxyType, data URLs in uri parts, lone surrogates and integer keys all export with no media.

One path does leak blob bytes, though, so this needs a fix before merge.

🔴 Blocker

Blob bytes leak as base64 when the encoder refuses the value (src/rius/normalization.py:1242-1247, src/rius/_serde.py:352-367)

_plain_content turns a blob part's bytes into a base64 string before encoding. If json_text then fails (a cycle, or a key that is not str/int/float/bool/None, such as bytes, tuple, datetime or UUID), it falls back to safe_repr(plain). That output is a Python repr, not JSON. The media rebuild can't parse it, and strip_raw_payload doesn't treat a bare base64 run as media below the budget. So the image's base64 is exported verbatim. Before this PR, the same bytes would have been a bytes literal, and safe_repr turns those into markers.

Repro (OTel 1.45, through NormalizingSpanExporter):

blob = {"type": "blob", "mime_type": "image/png", "content": PNG}
cyc = [{"role": "user", "parts": [blob]}]; cyc[0]["self"] = cyc
# exported: "[{'role': 'user', 'parts': [{'type': 'blob', ..., 'content': 'iVBORw0KGgo...'
[{b"k": 1, "type": "blob", "content": PNG}]   # same leak via a bytes key

Cycles in message lists are unlikely, but the contract says bytes never leave, and this path breaks it silently. The existing tests miss it because test_a_value_that_cannot_be_encoded_never_fails_the_export (tests/…structured_content.py:185) and test_a_byte_key_never_fails_the_export_or_leaks_its_bytes (:193) never put a blob in the same value.

Suggestion: only use the base64 form when it encodes. For example, in structured_content_as_json, call _bounded_dumps(plain, _unchanged) inside a try, and on any exception use json_text(value) on the original value. Its repr then writes the bytes as markers, which I checked: cycle_bytes_outside gives [stripped unknown 10248 bytes]. Add a regression test with a blob in a cycle and in a bytes-keyed map.

🟡 Suggestions

Span events carrying the same keys as structured values still leak a blob's base64 string (src/rius/normalization.py:1355, events go through strip_media only)

The PR says events are unchanged and that byte objects inside maps become markers, which is true. But a structured blob whose content is already a base64 string (the form the JSON carries) passes through attribute_value untouched. The bare string isn't recognised as media:

span.add_event("gen_ai.client.inference.operation.details",
    {"gen_ai.output.messages": [{"role": "assistant", "parts": [
        {"type": "blob", "mime_type": "image/png", "content": B64}]}]})
# exported event attribute still contains 'iVBORw0KGgo...'

This was already true before this PR, but it's the same class of gap the ticket closes for span attributes, and OTel 1.45 keeps maps on event attributes too. The fix is cheap: run structured_content_as_json on event attributes before _stripped_events. If you'd rather keep this PR narrow, a follow-up ticket works too.

Integral and small-exponent floats aren't byte-identical with TypeScript. The json encoder writes 1.0, 1e-07 and -0.0, while JSON.stringify writes 1, 1e-7 and 0. I ran the same tool definition through both SDKs and the outputs differed. This was already true of serialize. But structured values from Python instrumentations will carry floats like 2.0 and 0.0 often (tool-call arguments, JSON Schema defaults), so the "byte for byte" claim in both PR bodies doesn't hold in general. The shared cases only use 2 and 21.5, which is why they pass. Either document it as a known divergence in the contract, or normalise integral floats in _bounded_dumps (that would also change serialize, so it's probably a separate change).

💭 Nits

  • The body says Closes RIUS-1874 while the TS port and feat: normalize third-party attribute keys onto the canonical wire #113 say Related. Merging this one first will close the ticket before the TypeScript side lands.
  • The json_text docstring ("its bytes literals markers, for the strip to read") describes the fallback correctly for raw bytes, but not for the base64 that _plain_content already wrote. It should be updated along with the fix above.

Good work on the mutation checks and on testing the floor job with a real-tracer skip. With the fallback fixed, this is ready from my side.

…ncoded

A blob part's bytes were written as base64 before encoding. When the encoder
then refused the value (a cycle, a bytes or tuple key), the fallback was the
repr of that converted value, where the base64 is a bare string the media
rebuild and the strip do not read, so the image was exported. The base64
form is now kept only when the whole value encodes; otherwise the fallback
is the text of the value as it came, whose byte objects are markers.

Re-vendor sdk_cases with the lone byte object, float, data URL and nested
blob cases.
@PabloPardoGarcia

Copy link
Copy Markdown
Member Author

Addressed in d7920b3:

  • Blocker fixed. The base64 form of a blob's bytes is used only when the whole value encodes (_serde.strict_json_text). Otherwise the fallback is the repr of the value as it came, so its bytes are markers. No other path carries the converted value: _plain_content is only used there, and the _finite retry stays JSON. Regression tests go through NormalizingSpanExporter with a blob in a cyclic message list, beside a bytes key and beside a tuple key. All 3 exported the base64 before the fix.
  • json_text docstring updated.
  • Span events with structured keys and the float text difference are listed in the body as known follow-ups. The shared cases now say a float's text is per SDK (rius-semconv#113).
  • Re-vendored sdk_cases at de35796 (16 cases). ruff, format, mypy and pytest (2936 passed) all pass.

@PabloPardoGarcia

Copy link
Copy Markdown
Member Author

Landed through #289, together with the rius-semconv v1.13.0 sync.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant